using System;
using System.Web.UI.WebControls;
using Microsoft.SharePoint;
using Microsoft.SharePoint.Utilities;
using Microsoft.SharePoint.WebControls;
using Ventigrate.Shared.ExternalMembership.Internal;
using SWS = System.Web.Security;

namespace Ventigrate.Shared.ExternalMembership.WebControls
{
    /// <summary>
    /// Code behind for UserEdit.aspx
    /// </summary>
    public class UserEdit : LayoutsPageBase
    {
        protected InputFormSection RolesSection;
        protected InputFormSection PasswordSection;
        protected InputFormCheckBoxList rolesList;
        protected InputFormCheckBox isActive;
        protected InputFormTextBox txtEmail;
        protected InputFormTextBox txtDescription;
        protected Label lblCurrentPassword;
        protected InputFormTextBox txtPassword;
        protected InputFormTextBox txtUsername;
        protected Label lblMessage;

        protected override bool RequireSiteAdministrator
        {
            get { return true; }
        }

        private ExtranetContext _ctx = null;
        internal ExtranetContext Ctx
        {
            get
            {
                if (null == _ctx)
                    _ctx = ExtranetContext.Default;

                return _ctx;
            }
        }

        protected override void OnLoad(EventArgs e)
        {
            // init
            this.CheckRights();

            // hide/show password section
            PasswordSection.Visible = Membership.EnablePasswordRetrieval;

            // get user info
            string userName = this.Request.QueryString["USERNAME"];
            SWS.MembershipUser user = Membership.GetUser(userName);

            if (user != null)
            {
                if (!Page.IsPostBack)
                {
                    // load user props
                    lblCurrentPassword.Text = SWS.Membership.EnablePasswordRetrieval ? user.GetPassword() : null;
                    txtEmail.Text = user.Email;
                    txtDescription.Text = user.Comment;
                    txtUsername.Text = user.UserName;
                    isActive.Checked = user.IsApproved;

                    // if roles activated display roles
                    if (Ctx.RoleProvider != null)
                    {
                        RolesSection.Visible = true;

                        try
                        {
                            // load roles
                            string[] roles = Roles.GetAllRoles();
                            rolesList.DataSource = roles;
                            rolesList.DataBind();

                            // select roles associated with the user
                            for (int i = 0; i < roles.Length; i++)
                            {
                                rolesList.Items.FindByText(roles[i].ToString()).Selected = Roles.IsUserInRole(user.UserName, roles[i].ToString());
                            }
                        }
                        catch (Exception ex)
                        {
                            ULS.Log.Error(ex);
                            SPUtility.TransferToErrorPage(ex.Message); 
                        }
                    }
                }
            }
            else
            {
                SPUtility.TransferToErrorPage("User Not Found");
            }
        }

        protected void OnSubmit(object sender, EventArgs e)
        {
            // get user info
            string userName = this.Request.QueryString["USERNAME"];
            SWS.MembershipUser user = Membership.GetUser(userName);

            // check user exists
            if (user != null)
            {
                try
                {
                    // update membership provider info
                    user.Email = txtEmail.Text;
                    user.Comment = txtDescription.Text;
                    user.IsApproved = isActive.Checked;
                    Membership.UpdateUser(user);

                    // new password
                    if (!String.IsNullOrEmpty(txtPassword.Text))
                    {
                        user.ChangePassword(user.GetPassword(), txtPassword.Text);
                    }

                    // if roles enabled add/remove user to selected role(s)
                    if (Ctx.RoleProvider != null)
                    {
                        for (int i = 0; i < rolesList.Items.Count; i++)
                        {
                            if (rolesList.Items[i].Selected)
                            {
                                if (!Roles.IsUserInRole(user.UserName, rolesList.Items[i].Value))
                                    Roles.AddUserToRole(user.UserName, rolesList.Items[i].Value);
                            }
                            else
                            {
                                if (Roles.IsUserInRole(user.UserName, rolesList.Items[i].Value))
                                    Roles.RemoveUserFromRole(user.UserName, rolesList.Items[i].Value);
                            }
                        }
                    }
                    Response.Redirect("UsersDisp.aspx", false);
                }
                catch (Exception ex)
                {
                    ULS.Log.Error(ex);
                    SPUtility.TransferToErrorPage(ex.Message); 
                }
            }
            else
            {
                SPUtility.TransferToErrorPage("User Not Found");
            }
        }
    }
}
